package main

import (
	"fmt"
	"iec61850/device"
	"iec61850/master"
	"iec61850/slave"
	"time"
)

func main() {
	// 创建设备
	meterDevice := device.NewMeterDevice()
	inverterDevice := device.NewInverterDevice()

	// 创建并启动Slave
	slave := slave.NewSlave()
	slave.AddDevice(meterDevice)
	slave.AddDevice(inverterDevice)

	go func() {
		if err := slave.Start("0.0.0.0:102"); err != nil {
			fmt.Println("Failed to start slave:", err)
		}
	}()

	// 等待Slave启动
	time.Sleep(1 * time.Second)

	// 创建并连接Master
	Master := master.NewMaster()
	if err := Master.Connect("localhost:102"); err != nil {
		fmt.Println("Failed to connect to slave:", err)
		return
	}

	// MMS 示例
	fmt.Println("\nMMS 示例:")
	// 读取测量值
	measurements := map[string]float64{
		"Voltage": 220.5,
		"Current": 10.2,
	}
	if err := Master.MeasurementReport(measurements); err != nil {
		fmt.Println("MMS Measurement Report Error:", err)
	}

	// 读取属性
	attributes, err := Master.ReadAttributes()
	if err != nil {
		fmt.Println("MMS Read Attributes Error:", err)
	} else {
		fmt.Println("Device Attributes:", attributes)
	}

	// GOOSE 示例
	fmt.Println("\nGOOSE 示例:")
	// 创建GOOSE发布者
	goosePublisher := Master.NewGOOSEPublisher()
	gooseSubscriber := Master.NewGOOSESubscriber()

	// 订阅GOOSE消息
	go func() {
		if err := gooseSubscriber.Subscribe("localhost:20000", func(msg *master.GOOSEMessage) {
			fmt.Printf("Received GOOSE Message: %+v\n", msg)
		}); err != nil {
			fmt.Println("GOOSE Subscribe Error:", err)
		}
	}()

	// 发布GOOSE消息
	gooseData := map[string]interface{}{
		"Status": "Normal",
		"Alarm":  false,
	}
	if err := goosePublisher.Publish("localhost:20000", "APP001", "GOOSE001", gooseData); err != nil {
		fmt.Println("GOOSE Publish Error:", err)
	}

	// 保持程序运行
	select {}
}
